<template>
  <div class="app-container">
    <!-- 送货单维护 -->
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="searchForm" :inline="true">
        <el-form-item label="送货单号" prop="code">
          <el-input
            v-noSpace
            v-model="searchForm.code"
            class="!w-[192px]"
            clearable
            @keyup.enter="handleSearch"
            placeholder="请输入送货单号"
          />
        </el-form-item>

        <el-form-item label="送货人" prop="deliveryUser">
          <el-select
            v-model="searchForm.deliveryUser"
            placeholder="请输入送货人"
            @change="handleSearch"
            class="!w-[192px]"
            clearable
          >
            <el-option
              v-for="item in plateList"
              :key="item.id"
              :label="item.driverName"
              :value="item.id.toString()"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="车牌号" prop="licensePlate">
          <el-select
            v-model="searchForm.licensePlate"
            placeholder="请选择车牌号"
            class="!w-48"
            clearable
            @change="handleSearch"
          >
            <el-option
              v-for="item in plateList"
              :key="item.licensePlate"
              :label="item.licensePlate"
              :value="item.licensePlate"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            class="!w-[192px]"
            clearable
            @change="handleSearch"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="送货日期" prop="timeScopes">
          <el-date-picker
            v-model="searchForm.timeScopes"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            class="!w-80"
            clearable
            @change="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleSearch">搜索</el-button>
          <el-button
            type="warning"
            icon="edit"
            @click="handleAdd"
            v-hasPerm="'sys:deliveryOrderMaintenance:edit'"
          >
            新增
          </el-button>
          <el-button icon="refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 送货单列表 -->
    <el-card shadow="never">
      <el-table
        :data="tableData"
        class="!rounded-button"
        show-overflow-tooltip
        @row-click="handleDeliveryOrderRowClick"
      >
        <el-table-column label="送货单号" align="center" width="200">
          <template #default="{ row }">
            <span class="text-primary font-medium">{{ row.code }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="销售订单"
          align="center"
          prop="salesOrderCodes"
          class="flex-center"
          width="120"
        />
        <el-table-column
          label="其他销售订单"
          align="center"
          prop="refCode"
          class="flex-center"
          width="200"
        /> -->
        <el-table-column
          label="车牌号"
          align="center"
          prop="licensePlate"
          class="flex-center"
          width="120"
        />

        <el-table-column
          label="司机"
          align="center"
          prop="driverName"
          class="flex-center"
          width="120"
        />
        <el-table-column
          label="联系电话"
          align="center"
          prop="driverPhone"
          class="flex-center"
          width="120"
        />
        <el-table-column
          label="装车位置"
          align="center"
          prop="loadingPosition"
          class="flex-center"
          width="120"
        />

        <el-table-column
          label="送货日期"
          align="center"
          prop="deliveryDate"
          class="flex-center"
          width="120"
        />
        <!-- <el-table-column
          label="单据日期"
          align="center"
          prop="issueDate"
          class="flex-center"
          width="120"
        /> -->
        <el-table-column label="状态" align="center" prop="status" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.status == 1" type="warning">待分配车辆</el-tag>
            <el-tag v-if="scope.row.status == 2" type="info">待上传报告</el-tag>
            <el-tag v-if="scope.row.status == 3" type="info">待审核</el-tag>
            <el-tag v-if="scope.row.status == 4" type="success">审核通过</el-tag>
            <el-tag v-if="scope.row.status == 5" type="danger">审核拒绝</el-tag>
            <el-tag v-if="scope.row.status == 6" type="info">取消送货</el-tag>
            <el-tag v-if="scope.row.status == 7" type="info">装车中</el-tag>
            <el-tag v-if="scope.row.status == 8" type="info">配送中</el-tag>
            <el-tag v-if="scope.row.status == 9" type="success">已完成</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="备注" align="center">
          <template #default="{ row }">
            {{ row.remark }}
          </template>
        </el-table-column>
        <el-table-column label="审核意见" prop="otherRef" align="center"></el-table-column>
        <el-table-column label="操作" align="center" width="300" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleOpenDialog(scope.row, 'look')">
              查看
            </el-button>
            <el-button
              v-hasPerm="'sys:deliveryOrderMaintenance:shipping'"
              v-if="scope.row.status == 7"
              type="primary"
              link
              @click="handleUploadSignReport(scope.row)"
            >
              装车完成
            </el-button>
            <el-button
              v-hasPerm="'sys:deliveryOrderMaintenance:delivery'"
              v-if="scope.row.status == 8"
              type="success"
              link
              @click.stop="handleUploadAttachReport(scope.row)"
            >
              送货完成
            </el-button>
            <el-button
              link
              type="warning"
              class="whitespace-nowrap"
              @click="handleEdit(scope.row)"
              v-if="scope.row.status < 3 || scope.row.status == 5"
              v-hasPerm="'sys:deliveryOrderMaintenance:car'"
            >
              分配车辆
            </el-button>
            <!-- <el-button
              link
              type="primary"
              class="whitespace-nowrap"
              @click="handleUploadReport(scope.row)"
              v-if="scope.row.status == 2 || scope.row.status == 5"
              v-hasPerm="'sys:deliveryOrderMaintenance:upload'"
            >
              上传报告
            </el-button> -->
            <el-button
              v-hasPerm="'sys:deliveryOrderMaintenance:upload'"
              link
              type="primary"
              class="whitespace-nowrap"
              @click="handleUploadReport(scope.row)"
              v-if="scope.row.status == 2 || scope.row.status == 5"
            >
              上传报告
            </el-button>
            <el-button
              link
              type="primary"
              class="whitespace-nowrap"
              @click="handleAuditDialog(scope.row)"
              v-if="scope.row.status == 3"
              v-hasPerm="'sys:deliveryOrderMaintenance:app'"
            >
              审核
            </el-button>

            <el-button
              link
              type="warning"
              class="whitespace-nowrap"
              @click.stop="handlePrintVisible(scope.row)"
              v-if="scope.row.status > 3 && scope.row.status !== 5 && scope.row.status !== 6"
              v-hasPerm="'sys:deliveryOrderMaintenance:print'"
            >
              打印
            </el-button>
            <el-button
              link
              type="danger"
              class="whitespace-nowrap"
              @click="deleteDeliveryOrder(scope.row.id)"
              v-if="scope.row.status !== 8 && scope.row.status !== 9"
              v-hasPerm="'sys:deliveryOrderMaintenance:del'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="searchForm.pageNum"
        v-model:limit="searchForm.pageSize"
        @pagination="handleSearch"
      />
    </el-card>
    <el-row :gutter="20">
      <!-- 订单列表 -->
      <el-col :lg="12" :xs="12" class="mt-2">
        <el-card shadow="never">
          <el-table
            class="!rounded-button"
            :data="deliveryOrderDetail"
            show-overflow-tooltip
            @row-click="handleRowClick"
          >
            <el-table-column label="订单号" align="center" width="200">
              <template #default="{ row }">
                <span class="text-primary font-medium">
                  {{ row.code }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              label="客户编号"
              align="center"
              prop="companyCode"
              class="flex-center"
            />
            <el-table-column
              label="客户名称"
              align="center"
              prop="customerName"
              class="flex-center"
            />
            <!-- <el-table-column
              label="联系人"
              align="center"
              prop="contactPerson"
              class="flex-center"
            />
            <el-table-column
              label="联系电话"
              align="center"
              prop="contactPhone"
              class="flex-center"
            /> -->
            <el-table-column label="送货地址" align="center" prop="shipCode" class="flex-center">
              <template #default="scope">
                {{ addressCodeFormat(scope.row.shipCode) }}
              </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="rowRemark" class="flex-center" />
          </el-table>

          <!-- 产品列表 -->
        </el-card>
      </el-col>
      <el-col :lg="12" :xs="12" class="mt-2">
        <el-card shadow="never">
          <el-table class="!rounded-button" show-overflow-tooltip :data="orderDetail">
            <el-table-column label="产品编号" align="center" prop="productCode" />
            <el-table-column label="产品名称" align="center" prop="productName">
              <template #default="scope">
                {{ productCodeFormat(scope.row.productCode) }}
              </template>
            </el-table-column>
            <el-table-column label="数量" align="center" prop="qty">
              <template #default="scope">
                {{ scope.row.qty }} {{ formatUnit(scope.row.unit) }}
              </template>
            </el-table-column>

            <el-table-column label="仓库" align="center" prop="warehouse" />
            <el-table-column label="操作" align="center" fixed="right">
              <template #default="scope">
                <el-button type="primary" link @click="handleBasketDetailDialog(scope.row)">
                  查看筐明细
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible.visible"
      :title="detailDialogVisible.title"
      width="800px"
      @close="handleCloseDialog"
    >
      <el-scrollbar max-height="500px">
        <el-form
          ref="formRef"
          :disabled="detailDialogVisible.type == 'look'"
          :model="formData"
          :rules="formRules"
          class="p-2"
          label-width="100px"
        >
          <div class="grid grid-cols-2 gap-2">
            <!-- 多选订单 -->
            <el-form-item label="订单号" prop="code">
              <el-select
                v-model="formData.code"
                placeholder="请选择订单号"
                class="w-full"
                filterable
                :disabled="detailDialogVisible.type == 'edit'"
                clearable
              >
                <el-option
                  v-for="item in salesOrderCodes"
                  :key="item.id"
                  :label="item.code"
                  :value="item.code || ''"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="司机" prop="deliveryUser">
              <el-select
                v-model="formData.deliveryUser"
                placeholder="请选择司机"
                class="w-full"
                clearable
                @change="handleChangeDriver"
              >
                <el-option
                  v-for="item in plateList"
                  :key="item.id"
                  :label="item.driverName"
                  :value="item.id.toString()"
                />
              </el-select>
            </el-form-item>
            <!-- 带出来车牌号 -->
            <el-form-item label="车牌号" prop="licensePlate">
              <el-input v-noSpace v-model="formData.licensePlate" disabled />
            </el-form-item>
            <!-- 带出来联系电话 -->
            <el-form-item label="联系电话" prop="driverPhone">
              <el-input v-noSpace v-model="formData.driverPhone" disabled />
            </el-form-item>

            <el-form-item label="装车车位" prop="loadingPosition">
              <el-select
                v-model="formData.loadingPosition"
                placeholder="请选择装车车位"
                class="w-full"
              >
                <el-option
                  v-for="item in positionList"
                  :key="item.parkingLocation"
                  :label="item.parkingLocation"
                  :value="item.parkingLocation"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="送货日期" prop="deliveryDate">
              <el-date-picker
                v-model="formData.deliveryDate"
                type="date"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                :disabled-date="disabledDate"
              />
            </el-form-item>
            <el-form-item label="备注" class="col-span-2" prop="remark">
              <el-input
                v-noSpace
                v-model="formData.remark"
                type="textarea"
                :rows="4"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>
          </div>
          <div v-if="detailDialogVisible.type == 'look'">
            <div class="bg-white rounded-lg p-6 shadow-sm">
              <h2 class="text-lg font-medium flex items-center gap-2">
                <el-icon class="text-primary"><Paperclip /></el-icon>
                车辆检查单
              </h2>
              <div>
                <div v-if="formData" class="!w-full">
                  <div style="width: 100%">
                    <div v-if="formData.inspectionReport">
                      <el-row
                        v-for="(item, index) in JSON.parse(formData.inspectionReport || '[]')"
                        :key="index"
                      >
                        <el-col :span="12">
                          <el-text type="primary">{{ item.name }}</el-text>
                        </el-col>
                        <el-col :span="12">
                          <el-link type="primary" @click="downloadFile(item.name, item.url)">
                            下载
                          </el-link>
                        </el-col>
                      </el-row>
                    </div>
                    <div v-else style="width: 100%">
                      <el-row>
                        <el-text type="primary">暂无附件</el-text>
                      </el-row>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div
              class="bg-white rounded-lg p-6 shadow-sm"
              v-if="detailDialogVisible.type == 'look'"
            >
              <h2 class="text-lg font-medium flex items-center gap-2">
                <el-icon class="text-primary"><Paperclip /></el-icon>
                司机签收记录
              </h2>

              <div style="width: 100%">
                <div v-if="formData.signReport">
                  <el-row
                    v-for="(item, index) in JSON.parse(formData.signReport || '[]')"
                    :key="index"
                  >
                    <el-col :span="12">
                      <el-text type="primary">{{ item.name }}</el-text>
                    </el-col>
                    <el-col :span="12">
                      <el-link type="primary" @click="downloadFile(item.name, item.url)">
                        下载
                      </el-link>
                    </el-col>
                  </el-row>
                </div>

                <div v-else style="width: 100%">
                  <el-row>
                    <el-text type="primary">暂无附件</el-text>
                  </el-row>
                </div>
              </div>
            </div>
            <div class="bg-white rounded-lg p-6 shadow-sm">
              <h2 class="text-lg font-medium flex items-center gap-2">
                <el-icon class="text-primary"><Paperclip /></el-icon>
                客户签收记录
              </h2>
              <div style="width: 100%">
                <div v-if="formData.otherAttachment">
                  <el-row
                    v-for="(item, index) in JSON.parse(formData.otherAttachment || '[]')"
                    :key="index"
                  >
                    <el-col :span="12">
                      <el-text type="primary">{{ item.name }}</el-text>
                    </el-col>
                    <el-col :span="12">
                      <el-link type="primary" @click="downloadFile(item.name, item.url)">
                        下载
                      </el-link>
                    </el-col>
                  </el-row>
                </div>
                <div v-else style="width: 100%">
                  <el-row>
                    <el-text type="primary">暂无附件</el-text>
                  </el-row>
                </div>
              </div>
            </div>
          </div>
        </el-form>

        <!-- <div class="bg-white rounded-lg p-6 shadow-sm">
          <div class="flex items-center justify-between mb-6">
            <h2 class="text-lg font-medium flex items-center gap-2">
              <el-icon class="text-primary"><Box /></el-icon>
              产品明细
            </h2>
          </div>
          <el-table :data="products">
            <el-table-column prop="code" label="产品编号" />
            <el-table-column prop="name" label="产品名称" />
            <el-table-column prop="basketIds" label="篮筐编号" />
            <el-table-column prop="basketCount" label="篮筐数量" />
            <el-table-column prop="grossWeight" label="毛重(kg)" />
            <el-table-column prop="netWeight" label="净重(kg)" />
          </el-table>
        </div> -->
      </el-scrollbar>
      <template #footer>
        <div v-if="detailDialogVisible.type !== 'look'" class="flex justify-center">
          <el-button @click="detailDialogVisible.visible = false">取消</el-button>
          <el-button type="primary" v-debounce="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 车辆轨迹对话框 -->
    <!-- <el-dialog v-model="vehicleTrackingVisible" title="车辆轨迹" width="800px">
      <el-text>车辆 {{ selectedDelivery.plateNumber }} 的轨迹地图</el-text>
      <div class="h-[400px] bg-gray-100 flex items-center justify-center">
        {{ selectedDeliveryPosition }}

        <div
          v-if="!selectedDeliveryPosition"
          class="w-full h-full flex items-center justify-center"
        >
          <el-text>车辆异常</el-text>
        </div>

        <Map
          v-else
          :options="[
            {
              currentPosition: selectedDeliveryPosition,
              startPosition: selectedDelivery.startPosition,
              targetPosition: selectedDelivery.deliveryCoordinates,
              pathLine: selectedDelivery.pathLine, // 轨迹路径坐标点数组
            },
          ]"
        />
      </div>
    </el-dialog> -->
    <!-- 上传车辆检查报告 -->
    <el-dialog
      v-model="uploadReport.visible"
      title="上传报告"
      width="600"
      @close="handleCloseUploadReport"
    >
      <template #header>
        <h2 class="text-lg font-medium flex items-center gap-2">
          <el-icon class="text-primary"><Paperclip /></el-icon>
          车辆检查单
        </h2>
      </template>

      <div class="bg-white rounded-lg shadow-sm">
        <div>
          <FileUpload
            v-model:model-value="inspectionReport"
            uploadBtnText="点击上传"
            :showTip="true"
            :data="{ bizType: 'deliveryOrder' }"
            :maxSize="5 * 1024 * 1024"
            :showFileList="false"
            @update:model-value="handleUpdateFileInfoJson"
          />
        </div>
        <div v-if="inspectionReport" class="mt-4">
          <div
            v-for="(item, index) in JSON.parse(uploadReport.inspectionReport || '[]')"
            class="mt-4 flex gap-2 items-center"
          >
            <el-text type="primary">{{ item.name }}</el-text>
            <el-link type="primary" @click="downloadFile(item.name, item.url as string)">
              下载
            </el-link>
            <el-button link type="danger" @click="handleDeleteReport(index)">删除</el-button>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button type="primary" @click="handleSubmitReport">确认</el-button>
      </template>
    </el-dialog>
    <!-- 审核弹窗 -->
    <el-dialog
      v-model="auditDialog.visible"
      title="审核"
      width="400"
      @close="handleCloseAuditDialog"
    >
      <el-form :model="auditDialog">
        <el-form-item label="审核意见:">
          <el-input
            v-noSpace
            v-model="auditDialog.otherRef"
            type="textarea"
            :rows="3"
            :maxlength="120"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button type="primary" v-debounce="() => handleAudit('pass')">通过</el-button>

        <el-button v-debounce="() => handleAudit('noPass')">拒绝</el-button>
      </template>
    </el-dialog>
    <!--上传司机签收单  -->
    <el-dialog
      v-model="uploadSignReport.visible"
      title="上传报告"
      width="600"
      @close="handleCloseUploadSignReport"
    >
      <template #header>
        <h2 class="text-lg font-medium flex items-center gap-2">
          <el-icon class="text-primary"><Paperclip /></el-icon>
          司机签收单
        </h2>
      </template>

      <div class="bg-white rounded-lg shadow-sm">
        <div>
          <FileUpload
            v-model:model-value="signReport"
            uploadBtnText="点击上传"
            :showTip="true"
            :data="{ bizType: 'deliveryOrder' }"
            :maxSize="5 * 1024 * 1024"
            :showFileList="false"
          />
        </div>
        <div v-if="signReport" class="mt-4">
          <div v-for="(item, index) in signReport" class="mt-4 flex gap-2 items-center">
            <el-text type="primary">{{ item.name }}</el-text>
            <el-link type="primary" @click="downloadFile(item.name, item.url as string)">
              下载
            </el-link>
            <el-button link type="danger" @click="handleDeleteSignReport(index)">删除</el-button>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button type="primary" @click="handleSubmitSignReport">确认</el-button>
      </template>
    </el-dialog>
    <!-- 上传客户签收报告 -->
    <el-dialog
      v-model="uploadAttachReport.visible"
      title="上传报告"
      width="600"
      @close="handleCloseUploadAttachReport"
    >
      <template #header>
        <h2 class="text-lg font-medium flex items-center gap-2">
          <el-icon class="text-primary"><Paperclip /></el-icon>
          客户签收记录
        </h2>
      </template>

      <div class="bg-white rounded-lg shadow-sm">
        <div>
          <FileUpload
            v-model:model-value="attachment"
            uploadBtnText="点击上传"
            :showTip="true"
            :data="{ bizType: 'deliveryOrder' }"
            :maxSize="5 * 1024 * 1024"
            :showFileList="false"
          />
        </div>
        <div v-if="attachment" class="mt-4">
          <div v-for="(item, index) in attachment" class="mt-4 flex gap-2 items-center">
            <el-text type="primary">{{ item.name }}</el-text>
            <el-link type="primary" @click="downloadFile(item.name, item.url as string)">
              下载
            </el-link>
            <el-button link type="danger" @click="handleDeleteAttachment(index)">删除</el-button>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button type="primary" v-debounce="handleSubmitAttachReport">确认</el-button>
      </template>
    </el-dialog>
    <!-- 查看筐 -->
    <el-dialog v-model="basketVisible" title="筐明细" width="600">
      <el-table :data="basketList">
        <el-table-column prop="basket" label="筐号" />
        <el-table-column prop="qty" label="数量">
          <template #default="scope">
            <div>
              {{ scope.row.qty }}
              {{ formatUnit(scope.row.unit) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="location" label="储位" />
      </el-table>
    </el-dialog>
    <!-- 查看打印预览 -->
    <el-dialog v-model="printVisible" title="打印预览" @close="handleClosePrint">
      <div class="border">
        <printCard :print-data="printData" id="printContent"></printCard>
      </div>

      <template #footer>
        <el-button type="primary" v-print="handlePrint">打印</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";

import { formatUnit } from "@/utils/formatUnit";
import FileAPI from "@/api/file";
import { UploadUserFile } from "element-plus/es/components/upload/src/upload";
import deliveryOrderMaintenanceApi, {
  DeliveryOrderList,
  DeliveryOrderListQuery,
  SalesOrderDeliveryPlanDetail,
} from "@/api/LogisticsManagement/deliveryOrderMaintenance";
import { FormItemRule } from "element-plus";
import vehicleMonitoringDataApi from "@/api/LogisticsManagement/vehicleMonitoringData";
import parkingSpaceInquiryApi, {
  parkingSpaceInquiryResult,
} from "@/api/LogisticsManagement/parkingSpaceInquiry";
import SalesAPI, { SalesPageQueryPageVO } from "@/api/order/sales";
import stockOutApi from "@/api/warehouseManage/stockOut";

import configApi from "@/api/config/config";
import printCard from "./components/printCard.vue";
import cusInfoApi from "@/api/cusManage/cusInfo";

const basketVisible = ref(false);
//上传报告弹窗
const uploadReport = ref({
  visible: false,
  id: NaN,
  inspectionReport: "",
});

//车辆检查单
const handleUploadReport = (row: DeliveryOrderList) => {
  uploadReport.value.visible = true;
  uploadReport.value.id = row.id;
};
const inspectionReport = ref<UploadUserFile[]>([]);

const handleSubmitReport = async () => {
  if (inspectionReport.value.length === 0) {
    ElMessage.error("请选择文件");
    return;
  }
  try {
    await deliveryOrderMaintenanceApi.saveOrUpdateDeliveryOrder({
      id: uploadReport.value.id,
      status: 3,
      inspectionReport: uploadReport.value.inspectionReport,
    });
    ElMessage.success("上传成功");
    handleSearch();
    uploadReport.value.visible = false;
    uploadReport.value.inspectionReport = "";
    uploadReport.value.id = NaN;
    inspectionReport.value = [];
  } catch (error) {
    console.log(error);
  }
};

const handleCloseUploadReport = () => {
  inspectionReport.value = [];
};
// 上传司机签收单
const uploadSignReport = ref({
  visible: false,
  id: NaN,
  loadingPosition: "",
  sourceCode: "",
  signReport: "",
});
const handleUploadSignReport = (row: DeliveryOrderList) => {
  uploadSignReport.value.visible = true;
  uploadSignReport.value.id = row.id;
  uploadSignReport.value.loadingPosition = row.loadingPosition;
  uploadSignReport.value.sourceCode = row.code;
};
const signReport = ref<UploadUserFile[]>([]);
const handleSubmitSignReport = async () => {
  if (signReport.value.length === 0) {
    ElMessage.error("请上传司机签收单");
    return;
  }
  try {
    await deliveryOrderMaintenanceApi.saveOrUpdateDeliveryOrder({
      id: uploadSignReport.value.id,
      signReport: uploadSignReport.value.signReport,
    });
    await handleLoadingCompletion(
      uploadSignReport.value.id,
      uploadSignReport.value.loadingPosition,
      uploadSignReport.value.sourceCode
    );
    ElMessage.success("上传成功");
    uploadSignReport.value.visible = false;
    signReport.value = [];
  } catch (error) {
    console.log(error);
  }
};

const handleCloseUploadSignReport = () => {
  signReport.value = [];
};

//客户签收单
const uploadAttachReport = ref({
  visible: false,
  id: NaN,
  loadingPosition: "",
  attachment: "",
});
const handleUploadAttachReport = (row: DeliveryOrderList) => {
  uploadAttachReport.value.visible = true;
  uploadAttachReport.value.id = row.id;
};
const attachment = ref<UploadUserFile[]>([]);
const handleSubmitAttachReport = async () => {
  if (attachment.value.length === 0) {
    ElMessage.error("请上传客户签收记录");
    return;
  }
  try {
    await handleDeliveryCompletion(uploadAttachReport.value.id, JSON.stringify(attachment.value));
    uploadAttachReport.value.visible = false;
    attachment.value = [];
  } catch (error) {
    console.log(error);
  }
};
const handleCloseUploadAttachReport = () => {
  attachment.value = [];
};

const disabledDate = (time: Date) => {
  const startDate = new Date();
  startDate.setHours(0, 0, 0, 0); // 设置开始日期为当天的开始时间
  return time.getTime() < startDate.getTime();
};
const formRef = ref();
const total = ref(0);
const detailDialogVisible = ref({
  title: "",
  type: "",
  visible: false,
});
const vehicleTrackingVisible = ref(false);
const selectedDelivery = ref<any>(null);

const formData = ref<
  DeliveryOrderList & {
    licensePlate: string;
    driverPhone: string;
    completionTime: string;
  }
>({
  billCode: "", //单据编码
  code: "", //编号
  companyCode: "", //客户编号
  companyName: "", //客户名称
  deliveryDate: "", //送货日期
  deliveryUser: "", //送货人
  driverName: "", //司机姓名
  genNo: NaN, //生成单号
  id: NaN, //ID
  issueDate: "", //单据日期
  otherRef: "", //其他参考
  parentCategory: NaN, //父级分类
  parentCode: "", //父级编码
  prefix: "", //前缀
  refCode: "", //参考编码
  remark: "", //备注
  salesDeliveryDetailList: [], //送货单明细列表
  salesOrderCodes: "", //销售订单编码列表
  status: NaN, //状态
  statusList: [], //状态列表
  timeScopes: [], //时间范围
  licensePlate: "", //车牌号
  loadingPosition: "", //装车位置
  driverPhone: "", //司机电话
  completionTime: "", //装车完成时间
});
const formRules = reactive<Record<string, FormItemRule[]>>({
  salesOrderCodes: [{ required: true, message: "订单号不能为空", trigger: "blur" }],
  deliveryUser: [{ required: true, message: "请选择司机", trigger: "blur" }],

  loadingPosition: [{ required: true, message: "请选择装车车位", trigger: "blur" }],
  deliveryDate: [{ required: true, message: "请选择送货日期", trigger: "change" }],
});

const fileInfoJson = ref<UploadUserFile[]>([]);

//车牌数据
const plateList = ref<
  {
    id: number;
    driverName: string;
    licensePlate: string;
    contactInfo: string;
  }[]
>([]);
//获取所有车
const getPlateList = () => {
  vehicleMonitoringDataApi.getVehicleMonitoring({ pageNum: 1, pageSize: 999 }).then((res: any) => {
    plateList.value = res.list.map((item: any) => ({
      id: item.id,
      driverName: item.driverName,
      licensePlate: item.licensePlate,
      contactInfo: item.contactInfo,
    }));
  });
};

//选择司机时触发的事件
const handleChangeDriver = (value: string) => {
  const driver = plateList.value.find((item) => item.id === Number(value));

  if (driver) {
    formData.value.licensePlate = driver.licensePlate;
    formData.value.driverPhone = driver.contactInfo;
    formData.value.deliveryUser = driver.id.toString();
    formData.value.driverName = driver.driverName;
  }
};

//所有状态
const statusOptions = ref([
  { value: 1, label: "待分配" },
  { value: 2, label: "待上传报告" },
  { value: 3, label: "待审核" },
  { value: 4, label: "审核通过" },
  { value: 5, label: "审核拒绝" },
  { value: 6, label: "取消送货" },
  { value: 7, label: "装车中" },
  { value: 8, label: "配送中" },
  { value: 9, label: "已完成" },
  { value: 10, label: "已退货" },
]);

//车位数据
const positionList = ref<parkingSpaceInquiryResult[]>([]);

//获取所有装车位
const getPositionList = () => {
  parkingSpaceInquiryApi.pageQuery({ pageNum: 1, pageSize: 999, spotType: 0 }).then((res) => {
    positionList.value = res.list;
  });
};

//获取所有订单
const salesOrderCodes = ref<SalesPageQueryPageVO[]>([]);
const getSalesOrderList = () => {
  SalesAPI.getPage({ isReturnOrder: 0, pageNum: 1, pageSize: 999, status: "4" }).then(
    (res: any) => {
      salesOrderCodes.value = res.list;
    }
  );
};

const tableData = ref<DeliveryOrderList[]>([]);

const searchForm = ref<DeliveryOrderListQuery>({
  pageNum: 1,
  pageSize: 10,
});

const handleSearch = () => {
  //清空所有数据
  deliveryOrderDetail.value = [];
  orderDetail.value = [];
  tableData.value = [];
  total.value = 0;
  // 处理搜索
  deliveryOrderMaintenanceApi.getDeliveryOrderList(searchForm.value).then((res: any) => {
    console.log(res, "res.list", res.list);

    tableData.value = res.list;
    total.value = res.total;
  });
};

//获取订单明细
const deliveryOrderDetail = ref<any>([]);
const orderDetail = ref<SalesOrderDeliveryPlanDetail[]>([]);
const getDeliveryOrderDetail = (code?: string) => {
  if (!code) return (deliveryOrderDetail.value = []);
  deliveryOrderMaintenanceApi.getDeliveryOrderDetail(code).then((res: any) => {
    getAddressListByCode(res.list);
  });
};

const getOrderDetail = (code: string) => {
  stockOutApi
    .getBottomPage({ pageNum: 1, pageSize: 1, parentCode: code })

    .then((res: any) => {
      orderDetail.value = res.detailList;
    });
};
//点击送货单行数据
const handleDeliveryOrderRowClick = (row: any) => {
  let saleCode = row.salesOrderCodes || row.refCode;
  getDeliveryOrderDetail(saleCode);
};

const handleOpenDialog = (row: any, type: string) => {
  getSalesOrderList();
  if (type === "add") {
    detailDialogVisible.value.visible = true;
    detailDialogVisible.value.type = "add";
    return;
  }
  if (type === "look") {
    detailDialogVisible.value.visible = true;
    detailDialogVisible.value.type = "look";
  } else if (type === "edit") {
    // 处理编辑
    detailDialogVisible.value.visible = true;
    detailDialogVisible.value.type = "edit";
  }
  Object.assign(formData.value, row);
};

//选择车辆位置
const selectedDeliveryPosition = ref<string>("");

//获取车辆位置
const handleGetLocation = (plateNumber: string) => {
  //送货地址deliveryCoordinates
  vehicleMonitoringDataApi
    .getVehicleMonitoring({ licensePlate: plateNumber, pageNum: 1, pageSize: 1 })
    .then((res: any) => {
      selectedDeliveryPosition.value = res.list[0].coordinates;
    });
};

//打印
const printVisible = ref(false);
const printData = ref<{
  deliveryInfo: {
    deliveryCode: string; //送货单号
    companyName: string; //客户名称
    companyCode: string; //客户编码
    companyAddress: string; //送货地址
    contactPerson: string; //联系人
    contactPhone: string; //联系电话
    deliveryDate: string; //送货日期
  };
  productList: Array<{
    productCode: string;
    productName: string; //商品名称
    qty: Number; //数量
    unit: string; //单位
    unitPrice: Number; //单价
  }>;
}>({
  deliveryInfo: {
    deliveryCode: "",
    companyName: "",
    companyCode: "",

    companyAddress: "",
    contactPerson: "",
    contactPhone: "",
    deliveryDate: "",
  },
  productList: [],
});

//打开打印弹窗
const handlePrintVisible = (row: DeliveryOrderList) => {
  let saleCode = row.salesOrderCodes || row.refCode;
  deliveryOrderMaintenanceApi
    .getDeliveryOrderDetail(saleCode)
    .then((res: any) => {
      printData.value.deliveryInfo = {
        deliveryCode: row.code,
        companyName: res.list?.[0].customerName || "",
        companyCode: res.list?.[0].companyCode,

        companyAddress: res.list?.[0].address,
        contactPerson: res.list?.[0].contactPerson,
        contactPhone: res.list?.[0].contactPhone,
        deliveryDate: row.deliveryDate,
      };
    })
    .then(() => {
      stockOutApi
        .getPage({ pageNum: 1, pageSize: 1, sourceCategory: "5", sourceCode: saleCode })
        .then((data: any) => {
          stockOutApi
            .getRowPage({ pageNum: 1, pageSize: 10, parentCode: data.list?.[0]?.code })
            .then((resp: any) => {
              resp.list.forEach((ele: any) => {
                printData.value.productList?.push({
                  productCode: ele?.productCode,
                  productName: productCodeFormat(ele?.productCode),
                  qty: ele?.qty,
                  unit: ele?.unit,
                  unitPrice: ele?.unitPrice,
                });
              });
              console.log(printData.value.productList);

              printVisible.value = true;
            });
          // getOutProduct(res.list?.[0]?.code);
          //  printData.value.productList = {};
          // printVisible.value = true;
        });
    });
};

//关闭打印弹窗
const handleClosePrint = () => {
  printData.value.productList = [];
  printData.value.deliveryInfo = {
    companyCode: "",
    deliveryCode: "",
    companyName: "",
    companyAddress: "",
    contactPerson: "",
    contactPhone: "",
    deliveryDate: "",
  };
  printVisible.value = false;
};

const handlePrint = {
  id: "printContent", // 必填：要打印的DOM元素ID
  popupTitle: "送货单打印", // 可选：打印窗口标题

  beforeOpenCallback: () => {
    console.log("打印窗口打开前");
  },
  closeCallback: () => {
    console.log("打印窗口关闭后");
  },
};
const handleEdit = (row: any) => {
  // 处理编辑
  handleOpenDialog(row, "edit");
};

const handleBasketDetailDialog = (row: any) => {
  basketVisible.value = true;
  getBasketDetail(row.code, row.unit);
};

//根据销售订单获取出库单
const getStockOut = (saleCode: string, unit: string) => {
  stockOutApi
    .getPage({ pageNum: 1, pageSize: 1, sourceCategory: "5", sourceCode: saleCode })
    .then((res: any) => {
      getOutProduct(res.list?.[0]?.code);
      // getBasketDetail(res.list[0].code, unit);
    });
};
//获取出库产品
const getOutProduct = (outCode?: string) => {
  if (!outCode) return (orderDetail.value = []);
  stockOutApi.getRowPage({ pageNum: 1, pageSize: 10, parentCode: outCode }).then((res: any) => {
    orderDetail.value = res.list;
  });
};
const productList = ref<
  {
    label: string;
    value: string;
    unit: string;
  }[]
>([]);
// 获取产品列表
const getProductName = () => {
  configApi.getProductList({ pageNum: 1, pageSize: 999 }).then((data) => {
    productList.value = data?.list.map((item: any) => {
      return { label: item.productName, value: item.code, unit: item.unit };
    });
  });
};
//根据产品编号获取产品
const productCodeFormat = (productCode: string) => {
  let data = productList.value.find((item) => item.value == productCode);

  if (!data) {
    return "-";
  }
  return data?.label;
};

//根据客户编号获取地址信息
const addressList = ref([]);
const getAddressListByCode = (list: Array<any>) => {
  if (!list[0].companyCode) return (addressList.value = []);

  cusInfoApi
    .getAddressPage({ pageNum: 1, pageSize: 999, parentCode: list[0].companyCode })
    .then((data) => {
      console.log(data, "getAddressListByCode");
      addressList.value = data;
    })
    .then(() => {
      deliveryOrderDetail.value = list;
      formData.value.salesOrderCodes = list[0].refCode;
      getOrderDetail(deliveryOrderDetail.value[0].code);
    });
};

//根据地址编号获取地址名称
const addressCodeFormat = (addressCode: string) => {
  let data: any = addressList.value?.find((item: any) => item.code == addressCode);
  console.log(addressList.value, "addressList", addressCode, "addressCode");

  if (!data) {
    return "-";
  }
  return data.address;
};

//筐列表分页
const basketPage = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
  parentCode: "",
});
const basketList = ref([]);
//获取产品筐明细
const getBasketDetail = (code: string, unit: string) => {
  basketPage.parentCode = code;
  stockOutApi.getBottomPage(basketPage).then((res: any) => {
    basketList.value = res.list;
    basketList.value.map((item: any) => {
      item.unit = unit;
    });
    basketPage.total = res.total;
  });
};

// 处理提交
const handleSubmit = () => {
  //表单校验
  formRef.value.validate((valid: any) => {
    if (valid) {
      formData.value.status = 2; // 提交时将状态设置为2

      formData.value.refCode = formData.value.salesOrderCodes;
      deliveryOrderMaintenanceApi.saveOrUpdateDeliveryOrder(formData.value).then((res) => {
        ElMessage.success("提交成功");
        handleCloseDialog();
        handleSearch();
      });
    } else {
      ElMessage.error("请填写完整信息");
    }
  });
};
const queryFormRef = ref();
const handleReset = () => {
  queryFormRef.value?.resetFields();
  handleSearch();
};

function handleUpdateFileInfoJson(fileInfoJson: any) {
  let submitFileInfo = JSON.parse(uploadReport.value.inspectionReport || "[]");
  submitFileInfo = [fileInfoJson[fileInfoJson.length - 1], ...submitFileInfo];

  uploadReport.value.inspectionReport = JSON.stringify(submitFileInfo);
}

const handleDeleteReport = (index: number) => {
  let submitFileInfo = JSON.parse(uploadReport.value.inspectionReport || "[]");
  submitFileInfo.splice(index, 1);
  inspectionReport.value.splice(index, 1);
  uploadReport.value.inspectionReport = JSON.stringify(submitFileInfo);
};
const handleDeleteAttachment = (index: number) => {
  let submitFileInfo = JSON.parse(uploadAttachReport.value.attachment || "[]");
  submitFileInfo.splice(index, 1);
  attachment.value.splice(index, 1);
  uploadAttachReport.value.attachment = JSON.stringify(submitFileInfo);
};

const handleDeleteSignReport = (index: number) => {
  let submitFileInfo = JSON.parse(uploadSignReport.value.signReport || "[]");
  submitFileInfo.splice(index, 1);
  signReport.value.splice(index, 1);
  uploadSignReport.value.signReport = submitFileInfo;
};
// 下载文件
function downloadFile(name: string, filePath: string) {
  if (filePath) {
    FileAPI.downloadFile(filePath, name)
      .then((res) => {
        ElMessage.success("下载成功");
      })
      .catch((err) => {
        // ElMessage.error(`${err}`);
      });
  } else {
    ElMessage.error("文件不存在");
  }
}

//审核弹窗
const auditDialog = ref({
  visible: false,
  id: NaN,
  status: NaN,
  code: "",
  loadingPosition: "", //装车位置
  licensePlate: "", //车牌号
  otherRef: "", //审核意见
});

const handleCloseAuditDialog = () => {
  auditDialog.value = {
    visible: false,
    id: NaN,
    status: NaN,
    code: "",
    loadingPosition: "", //装车位置
    licensePlate: "", //车牌号
    otherRef: "", //审核意见
  };
};

//打开审核弹窗
const handleAuditDialog = (row: any) => {
  auditDialog.value.visible = true;
  auditDialog.value.id = row.id;
  auditDialog.value.status = row.status;
  auditDialog.value.code = row.code;
  auditDialog.value.loadingPosition = row.loadingPosition; //装车位置
  auditDialog.value.licensePlate = row.licensePlate; //车牌号
};
const outCode = ref();
const handleRowClick = (row: any) => {
  //根据销售单获取出库单
  getStockOut(row.code, row.unit);
};

//审核通过或拒绝
const handleAudit = useDebounceFn((type: "pass" | "noPass") => {
  let status = type === "pass" ? 7 : 5;

  deliveryOrderMaintenanceApi
    .saveOrUpdateDeliveryOrder({ id: auditDialog.value.id, status })
    .then((res) => {
      if (type === "pass") {
        parkingSpaceInquiryApi
          .saveOrUpdate({
            parkingLocation: auditDialog.value.loadingPosition,
            licensePlate: auditDialog.value.licensePlate,
            sourceCode: auditDialog.value.code,
            spotType: 0,
          })
          .then(() => {
            ElMessage.success("审核通过");
          });
      } else {
        ElMessage.success("审核拒绝");
      }
    })
    .catch((err) => {
      // ElMessage.error(`${err}`);
    })
    .finally(() => {
      auditDialog.value.id = NaN;
      auditDialog.value.status = NaN;
      auditDialog.value.visible = false;
      handleSearch();
    });
}, 1000);

//删除送货单
const deleteDeliveryOrder = (id: number) => {
  ElMessageBox.confirm("确定要删除该送货单吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deliveryOrderMaintenanceApi.deleteDeliveryOrder(id).then((res) => {
        ElMessage.success("删除成功");
        handleSearch();
      });
    })
    .catch(() => {});
};

//点击车牌打开vehicleTrackingVisible
function handleVehicleTracking(row: any) {
  vehicleTrackingVisible.value = true;
  selectedDelivery.value = row;
  handleGetLocation(row.plateNumber);
}

//打开弹窗
const handleAdd = () => {
  handleOpenDialog(null, "add");
};

// 关闭对话框
const handleCloseDialog = () => {
  detailDialogVisible.value.visible = false;
  //清空表单数据
  formData.value = {
    billCode: "", //单据编码
    code: "", //编号
    companyCode: "", //客户编号
    companyName: "", //客户名称
    deliveryDate: "", //送货日期
    deliveryUser: "", //送货人
    driverName: "", //司机姓名
    genNo: NaN, //生成单号
    id: NaN, //ID
    issueDate: "", //单据日期
    otherRef: "", //其他参考
    parentCategory: NaN, //父级分类
    parentCode: "", //父级编码
    prefix: "", //前缀
    refCode: "", //参考编码
    remark: "", //备注
    salesDeliveryDetailList: [], //送货单明细列表
    salesOrderCodes: "", //销售订单编码列表
    status: NaN, //状态
    statusList: [], //状态列表
    timeScopes: [], //时间范围
    licensePlate: "", //车牌号
    loadingPosition: "", //装车位置
    driverPhone: "", //司机电话
    completionTime: "", //装车完成时间
  };
};

//装车完成时触发的事件
const handleLoadingCompletion = async (id: number, loadingPosition: string, sourceCode: string) => {
  // 处理加载完成

  parkingSpaceInquiryApi
    .completeLoading(loadingPosition, sourceCode)
    .then((res) => {
      ElMessage.success("装车完成");
    })
    .then(async () => {
      await deliveryOrderMaintenanceApi.saveOrUpdateDeliveryOrder({
        id,
        status: 8,
      });
    })
    .finally(() => {
      handleSearch();
    });
};

//送货完成
const handleDeliveryCompletion = async (id: number, otherAttachment: string) => {
  deliveryOrderMaintenanceApi
    .saveOrUpdateDeliveryOrder({
      id,
      status: 9,
      otherAttachment: otherAttachment || null,
    })
    .then(() => {
      ElMessage.success("送货完成");
      handleSearch();
    });
};

onMounted(() => {
  // 初始化数据
  handleSearch();
  getPlateList();
  getPositionList();
  getProductName();
});
</script>

<style scoped></style>
